/*
 * @Description:
 * @Author: LCL
 * @Date: 2021-11-22
 * @LastEditors: LCL
 * @LastEditTime: 2021-12-01
 * @FilePath: /beff/src/components/drag/FrontEndEvent/ResultModal.tsx
 */

import { DeleteOutlined } from '@ant-design/icons';
import { Form, Modal, Tooltip } from 'antd';
import React, { useState, useEffect } from 'react';
import _ from 'lodash';
import styles from './index.less';
import InsertItem from './insertItem';
export type Options = { name: string; label: string; value: string };
interface IObj {
  name: string;
  value: string;
}
interface ModalFormProps {
  visible: boolean;
  options: Options[];
  resuletData: { name: string; value: string }[];
  setResultsObj: any;
  onCancel: () => void;
}

const ResultModal: React.FC<ModalFormProps> = ({
  visible,
  options,
  resuletData,
  setResultsObj,
  onCancel,
}) => {
  const [form] = Form.useForm();
  const [resultObj, setResultObj] = useState<Record<string, IObj>>({});
  const [toolVisible, setToolVisible] = useState(false);
  // const [actionRely, setActionRely] = useState<string[]>([]);
  const keys = Object.keys(resultObj);

  const getFieldList = (str: string) => {
    const pannet = /(?<=\$\{)[^}]*(?=\})/g;
    const newStr = str.match(pannet);
    return newStr;
  }
  const onOk = () => {
    const values = form.getFieldsValue();
    // const action_rely = [actionRely];
    let valueArry: any = Object.values(values)?.map((item: any) => {
      return getFieldList(item);
    })
    valueArry = _.flatten(valueArry) || [];
    const action_rely: string[] = _.uniq((valueArry).concat(keys));
    const arrKeys = Object.keys(values);
    let action: { name: string; value: string }[] = [];
    if (arrKeys.length) {
      action = arrKeys.map((item) => ({ name: item, value: values[item] }));
    }
    setResultsObj({ action, action_rely });
    form.submit();
  };
  const handleDelete = (id: string) => {
    const obj = { ...resultObj };
    delete obj[id];
    setResultObj(obj);
  };
  const getOptionDom = () => {
    let dom = <span style={{ color: '#000' }}>当前数据为空</span>;
    if (options && options.length) {
      const list = options.map((item) => {
        return (
          <li
            className={`${keys.includes(item.value) ? styles.menuDisable : styles.menuItem}`}
            key={item.value}
            onClick={() => {
              if (!keys.includes(item.value)) {
                const obj = { ...resultObj };
                obj[item.value] = { name: item.value, value: item.label };
                setResultObj(obj);
                setToolVisible(false);
              }
            }}
          >
            {item.label}
          </li>
        );
      });
      dom = <ul className={styles.menu}>{list}</ul>;
    }
    return dom;
  };
  // const onChange = (e) => {
  //   console.log(e.target);
  // };

  const list = Object.values(resultObj);
  useEffect(() => {
    const initialValue = {};
    const initialObj = {};
    const opionsObj = {};
    options.forEach((item) => (opionsObj[item.value] = item.label));
    if (resuletData.length) {
      resuletData.forEach((item) => {
        initialValue[item.name] = item.value;
        initialObj[item.name] = { name: item.name, value: opionsObj[item.name] };
      });
    }
    form.setFieldsValue(initialValue);
    setResultObj(initialObj);
  }, [form, options, resuletData]);

  return (
    <Modal
      title="返回值设置"
      visible={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={600}
      destroyOnClose={true}
    >
      <div className={styles.resWrapper}>
        <span>解析返回值并将其赋值给表单字段</span>
        <Form layout="vertical" preserve={false} form={form} name="resultForm">
          {list.map((item) => {
            const configProps = { label: item.value, name: item.name };
            return (
              <div className={styles.resBox} key={item.name}>
                <InsertItem configProps={configProps} options={options} type="textarea">
                  <div className={styles.insert}>插入字段</div>
                </InsertItem>
                {/* <Form.Item label={`「${item.value}」=`} name={item.name}>
                  <Input.TextArea
                    ref={setRef}
                    // onChange={onChange}
                    autoSize={{ minRows: 3, maxRows: 3 }}
                  />
                </Form.Item>
                <Tooltip title={getInsertDom()} trigger="click" color="#fff">
                  <div className={styles.insert}>插入字段</div>
                </Tooltip> */}
                <DeleteOutlined
                  onClick={() => {
                    handleDelete(item.name);
                  }}
                  className={styles.delete}
                />
              </div>
            );
          })}
        </Form>
        <Tooltip
          title={getOptionDom()}
          visible={toolVisible}
          trigger="click"
          color="#fff"
          placement="bottom"
          onVisibleChange={(data) => {
            setToolVisible(data);
          }}
        >
          <div className={styles.resBtn}>+ 表单字段及对应返回值</div>
        </Tooltip>
      </div>
    </Modal>
  );
};

export default React.memo(ResultModal);
